package ru.niir.goodfil.utils;

import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.isBlank;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.SQLQuery;

import java.util.List;
import java.util.ArrayList;

/**
 * Очень простой класс для построения запроса по шагам
 */
public class QueryBuilder
{
    private static Logger logger = Logger.getLogger(QueryBuilder.class);

    /**
     * Строка запроса
     */
    private String queryString;

    public String getQueryString()
    {
        return queryString;
    }

    /**
     * Параметры запроса
     */
    private final List<Object> params = new ArrayList<Object>();

    public static QueryBuilder WithWhere(String queryString)
    {
        assert !isBlank(queryString);
        return new QueryBuilder(queryString + " where 1=1 ");
    }

    public static QueryBuilder WithoutWhere(String queryString)
    {
        assert !isBlank(queryString);
        return new QueryBuilder(queryString);
    }

    private QueryBuilder(String queryString)
    {
        this.queryString = queryString;
    }

    public void addWhereCondition(String condition, Object param)
    {
        assert condition != null;
        assert param != null;
        assert condition.indexOf("?") == condition.lastIndexOf("?");
        assert condition.indexOf(":") == -1;

        this.queryString += (" and " + condition);
        params.add(param);
    }

    public void addWhereCondition(String condition)
    {
        assert condition != null;
        assert condition.indexOf("?") == -1;
        assert condition.indexOf(":") == -1;

        this.queryString += (" and " + condition);
    }

    public void appendText(String text)
    {
        this.queryString += (" " + text);
    }

    public Query toQuery(StatelessSession session)
    {
        assert session != null;

        logger.trace(queryString);

        Query q = session.createQuery(queryString);
        for (int i = 0; i < params.size(); i++)
            q.setParameter(i, params.get(i));

        return q;
    }

    public SQLQuery toSQLQuery(StatelessSession session)
    {
        assert session != null;

        logger.trace(queryString);

        SQLQuery q = session.createSQLQuery(queryString);
        for (int i = 0; i < params.size(); i++)
            q.setParameter(i, params.get(i));

        return q;
    }
}
